import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import ggbondImg from '@/assets/images/ggbond.png'

export const useOrderStore = defineStore('order', () => {
  // 订单列表
  const orders = reactive([
    {
      id: 1,
      orderNumber: 'BK202501190001',
      createTime: '2025-01-19 14:30:25',
      status: 'completed',
      totalAmount: 158.80,
      reviewed: false,
      items: [
        {
          id: 1,
          title: '星辰大海',
          author: '林宇辰',
          price: 59.80,
          quantity: 1,
          cover: ggbondImg
        },
        {
          id: 2,
          title: 'JavaScript高级程序设计',
          author: 'Nicholas C. Zakas',
          price: 99.00,
          quantity: 1,
          cover: ggbondImg
        }
      ]
    },
    {
      id: 2,
      orderNumber: 'BK202501180002',
      createTime: '2025-01-18 16:45:12',
      status: 'shipped',
      totalAmount: 88.00,
      reviewed: false,
      items: [
        {
          id: 3,
          title: '存在与时间',
          author: '马丁·海德格尔',
          price: 88.00,
          quantity: 1,
          cover: ggbondImg
        }
      ]
    },
    {
      id: 3,
      orderNumber: 'BK202501170003',
      createTime: '2025-01-17 10:20:30',
      status: 'paid',
      totalAmount: 156.00,
      reviewed: false,
      items: [
        {
          id: 4,
          title: '人类简史',
          author: '尤瓦尔·赫拉利',
          price: 68.00,
          quantity: 1,
          cover: ggbondImg
        },
        {
          id: 5,
          title: '未来简史',
          author: '尤瓦尔·赫拉利',
          price: 88.00,
          quantity: 1,
          cover: ggbondImg
        }
      ]
    },
    {
      id: 4,
      orderNumber: 'BK202501160004',
      createTime: '2025-01-16 18:15:45',
      status: 'pending',
      totalAmount: 45.00,
      reviewed: false,
      items: [
        {
          id: 6,
          title: '小王子',
          author: '安托万·德·圣-埃克苏佩里',
          price: 25.00,
          quantity: 1,
          cover: ggbondImg
        },
        {
          id: 7,
          title: '追风筝的人',
          author: '卡勒德·胡赛尼',
          price: 20.00,
          quantity: 1,
          cover: ggbondImg
        }
      ]
    },
    {
      id: 5,
      orderNumber: 'BK202501150005',
      createTime: '2025-01-15 20:30:15',
      status: 'cancelled',
      totalAmount: 128.00,
      reviewed: false,
      items: [
        {
          id: 8,
          title: '艺术的故事',
          author: '贡布里希',
          price: 128.00,
          quantity: 1,
          cover: ggbondImg
        }
      ]
    }
  ])

  // 订单计数器，用于生成新的订单ID
  const orderIdCounter = ref(6)

  // 生成订单号
  const generateOrderNumber = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const counter = String(orderIdCounter.value).padStart(4, '0')
    return `BK${year}${month}${day}${counter}`
  }

  // 格式化时间
  const formatDateTime = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 创建新订单
  const createOrder = (cartItems, totalAmount, paymentMethod = 'alipay') => {
    const newOrder = {
      id: orderIdCounter.value,
      orderNumber: generateOrderNumber(),
      createTime: formatDateTime(new Date()),
      status: 1, // 支付成功后的状态，使用数字1代表已支付，与后端保持一致
      totalAmount: totalAmount,
      reviewed: false,
      paymentMethod: paymentMethod,
      items: cartItems.map(item => ({
        id: item.id,
        title: item.title,
        author: item.author,
        price: item.price,
        quantity: item.quantity,
        cover: item.cover
      }))
    }

    // 添加到订单列表的开头（最新订单在前）
    orders.unshift(newOrder)
    orderIdCounter.value++

    return newOrder
  }

  // 获取订单列表
  const getOrders = () => {
    return orders
  }

  // 根据ID获取订单
  const getOrderById = (id) => {
    return orders.find(order => order.id === parseInt(id))
  }

  // 更新订单状态
  const updateOrderStatus = (orderId, status) => {
    const order = orders.find(o => o.id === orderId)
    if (order) {
      order.status = status
    }
  }

  // 标记订单已评价
  const markOrderReviewed = (orderId) => {
    const order = orders.find(o => o.id === orderId)
    if (order) {
      order.reviewed = true
    }
  }

  // 计算各状态订单数量
  const getOrderCounts = computed(() => {
    const counts = {
      all: orders.length,
      pending: 0,
      paid: 0,
      shipped: 0,
      completed: 0,
      cancelled: 0
    }

    orders.forEach(order => {
      if (counts[order.status] !== undefined) {
        counts[order.status]++
      }
    })

    return counts
  })

  return {
    orders,
    createOrder,
    getOrders,
    getOrderById,
    updateOrderStatus,
    markOrderReviewed,
    getOrderCounts
  }
})
